package org.study.timer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling
@EnableAsync
public class BirthdayWishesTask {

    @Autowired
    private EmailTool emailTool;

    @Scheduled(cron = "${email.run-time}")
    public void task() {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String today = simpleDateFormat.format(new Date());
        // 读取文件
        List<Staff> staffList = new ArrayList<>();
        File file = new File("birthday.txt");
        try {
            InputStreamReader inputReader = new InputStreamReader(new FileInputStream(file));
            BufferedReader bf = new BufferedReader(inputReader);
            // 按行读取字符串
            String str;
            while ((str = bf.readLine()) != null) {
                String tempStr = str.replace(" ", "");
                String[] array = tempStr.split(",");
                if (array.length != 3) {
                    System.out.println("invalid format of staff, record is " + str);
                    continue;
                }
                if (today.equals(array[2])) {
                    staffList.add(new Staff(array[0],array[1]));
                }
            }
            bf.close();
            inputReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("start...");
        long start = System.currentTimeMillis();
        staffList.forEach(s -> emailTool.sendBirthDayWishes(s.getName(),s.getId() + "@qq.com"));
        System.out.println("finished...");
        System.out.println(System.currentTimeMillis() - start);
    }
}

class Staff {

    private String id;
    private String name;

    public Staff(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}